 package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.WmNewsStatisticsDto;
import com.heima.model.media.pojos.WmNewsStatistics;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.media.vo.WmNewsStatisticsVo;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.feign.ArticleFeign;
import com.heima.wemedia.feign.BehaviorFeign;
import com.heima.wemedia.feign.UserFeign;
import com.heima.wemedia.mapper.WmNewsStatisticsMapper;
import com.heima.wemedia.service.WmNewsStatisticsService;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsStatisticsServiceImpl extends ServiceImpl<WmNewsStatisticsMapper, WmNewsStatistics> implements WmNewsStatisticsService {

    @Resource
    private ArticleFeign articleFeign;
    @Autowired
    private BehaviorFeign behaviorFeign;
    @Resource
    private UserFeign userFeign;
    @Resource
    private WmUserService wmUserService;

    /**
     * 查询统计数据
     */
    @Override
    public ResponseResult querySratistics(WmNewsStatisticsDto dto) {
        WmNewsStatisticsVo statisticsVo = new WmNewsStatisticsVo();
        log.info("==== 查询统计数据 ====  WmNewsStatisticsDto ===> {} ", dto);

        if (dto.getType() == -1) {
            // 检查参数
            if (!dto.getTime().isEmpty() && dto.getTime().size() > 0) {
                dto.setStime(dto.getTime().get(0));
                dto.setEtime(dto.getTime().get(1));
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
        } else {
            if ((dto.getStime() == null || dto.getStime().isEmpty())
                    && (dto.getEtime() == null || dto.getEtime().isEmpty())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            } else {
                // 将时间戳转换为  2021年3月3日11:35:26  格式
                dto.setStime(stampToDate(Long.valueOf(dto.getStime())));
                dto.setEtime(stampToDate(Long.valueOf(dto.getEtime())));
            }
        }


        //获取当前登录用户
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        WmUser wmUser = wmUserService.getById(user.getId());
        dto.setWmUserId(wmUser.getApUserId());
        log.info("获取当前用户信息 wmuser ==> {} ", wmUser);


        // 根据UserId查询当前用户发布的文章数   sTime  eTime
        Integer articleCount = articleFeign.findArticleCount(dto);
        //查询当前用户发布的所有文章的  ID集合   sTime  eTime
        List articleList = articleFeign.queryArticleIds(dto);

        List<ApReadBehavior> readBehaviorList = null;

        Integer readCount = 0;

        // 查询阅读行为表，统计阅读量
        if (!articleList.isEmpty() && articleList != null) {
            readBehaviorList = behaviorFeign.queryReadCount(articleList);
            //使用流计算阅读量
            readCount = readBehaviorList.stream().mapToInt(ApReadBehavior::getCount).sum();
        }

        // 先查询当前用户的粉丝ID 集合  ap_user_fans表  去重   list = [3,4,5,6]     sTime  eTime
        List fanList = userFeign.queryFansId(dto).stream().distinct().collect(Collectors.toList());

        // 查询粉丝的阅读量
        Integer fansReadCount = 0;

        if (!fanList.isEmpty() && fanList != null) {
            // 粉丝实体ID集合
            List fansEntryIdList = behaviorFeign.findFansEntryId(fanList);
            // 统计粉丝阅读量
            fansReadCount = readBehaviorList.stream()
                    .filter(m -> fansEntryIdList.contains(m.getEntryId()))
                    .mapToInt(ApReadBehavior::getCount).sum();
        }


        // 调用article的远程接口查询所有文章的评论数量
        List<ApArticle> apArticles = articleFeign.findArticleByAuthorId(dto);
        // 统计全部文章的总评论数
        Integer commentCount = apArticles.stream().mapToInt(apArticle->apArticle.getComment()==null?0:apArticle.getComment()).sum();


        //  封装饼图数据
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map1 = new LinkedHashMap<>();
        map1.put("value", articleCount);
        map1.put("name", "文章量");
        Map<String, Object> map2 = new LinkedHashMap<>();
        map2.put("value", readCount);
        map2.put("name", "阅读量");
        Map<String, Object> map3 = new LinkedHashMap<>();
        map3.put("value", fansReadCount);
        map3.put("name", "粉丝阅读量");
        Map<String, Object> map4 = new LinkedHashMap<>();
        map4.put("value", commentCount);
        map4.put("name", "评论量");
        Collections.addAll(list, map1, map2, map3, map4);
        // {data:[{value:7},{name:"文章量"}...] }
        Map<String, Object> objectMap = new HashMap<>();
        objectMap.put("data", list);

        System.out.println("==============  list =============== " + list);

        // 查询表格数据   最近5天的数据   。。。。。。。。。。。。。。。


        // 给vo对象赋值
        statisticsVo.setArticleNum(articleCount);
        statisticsVo.setReadNum(readCount);
        statisticsVo.setFanReadNum(fansReadCount);
        statisticsVo.setCommentNum(commentCount);
        statisticsVo.setChartList(objectMap);
        log.info("将要传回前端的数据  statisticsVo ==> {} ", statisticsVo);
        return ResponseResult.okResult(statisticsVo);
    }

    /**
     * 将时间戳转换为 具体时间
     */
    private String stampToDate(Long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time_Date = sdf.format(new Date(time));
        return time_Date;
    }
}

